/*
 * Copyright (c) 2022-2022 Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "los_pid_container.h"
#include "los_typedef.h"
#include "los_config.h"

#ifdef LOSCFG_PID_CONTAINER
struct PidContainer g_rootPidContainer = {};
extern struct ContainerConfig g_containerConfig;
UINT32 g_currentPidContainerNum = 1;


INT32 GetCurrPidLevel(VOID)
{
    return OsCurrProcessGet()->containerBundle->pidContainer->level;
}

INT32 GetVpid(VOID)
{
    UINT32 level = GetCurrPidLevel();
    return OsCurrProcessGet()->vProcessID.numbers[level].number;
}

INT32 GetVppid(VOID)
{
    UINT32 level = GetCurrPidLevel();
    UINT32 parentTopProcessID = OsCurrProcessGet()->parentProcessID;
    LosProcessCB *parentProcessCB = OS_PCB_FROM_PID(parentTopProcessID);

    return parentProcessCB->vProcessID.numbers[level].number;
}

INT32 GetGlobalPidByCurrPid(UINT32 pid)
{
    UINT32 globalPid = 0;
    UINT32 index = 0;
    UINT32 level = GetCurrPidLevel();
    LosProcessCB *runProcessCB = OsCurrProcessGet();
    if (level == PID_CONTAINER_ROOT_LEVEL) {
        globalPid = pid;
        return globalPid;
    }

    for (index = 0; index < LOSCFG_BASE_CORE_PROCESS_LIMIT; index++) {
        if (runProcessCB->containerBundle->pidContainer->vpidArray[index].vpid != pid) {
            continue;
        }
        if (runProcessCB->containerBundle->pidContainer->vpidArray[index].status != VPID_STATUS_USED) {
            break;
        }
        globalPid = runProcessCB->containerBundle->pidContainer->vpidArray[index].processCB->processID;
        LosProcessCB *processCB = runProcessCB->containerBundle->pidContainer->vpidArray[index].processCB;
        if (runProcessCB->containerBundle->pidContainer != processCB->vProcessID.numbers[level].ownerContainer) {
            break;
        }
        return globalPid;
    }
    return FINDGLOBALPID_ERR;
}

INT32 GetGloabalPidByContainerAndPcb(UINT32 pid)
{
    LosProcessCB *childCB = NULL;
    LosProcessCB *runProcessCB = OsCurrProcessGet();
    UINT32 level = runProcessCB->containerBundle->pidContainer->level;

    if (pid <= 0) {
        return pid;
    }
    if (level == PID_CONTAINER_ROOT_LEVEL) {
        return pid;
    }

    LOS_DL_LIST_FOR_EACH_ENTRY(childCB, &(runProcessCB->exitChildList), LosProcessCB, siblingList) {
        if ((childCB->vProcessID.numbers[level].number == pid)
            && (childCB->vProcessID.numbers[level].ownerContainer == runProcessCB->containerBundle->pidContainer)) {
            return childCB->processID;
        }
    }

    LOS_DL_LIST_FOR_EACH_ENTRY(childCB, &(runProcessCB->childrenList), LosProcessCB, siblingList) {
        if ((childCB->vProcessID.numbers[level].number == pid)
            && (childCB->vProcessID.numbers[level].ownerContainer == runProcessCB->containerBundle->pidContainer)) {
            return childCB->processID;
        }
    }
    return FINDGLOBALPID_ERR;

}

INT32 IsInSamePidContainer(LosProcessCB *processCB)
{
    UINT32 level = GetCurrPidLevel();
    if (level <= PID_CONTAINER_ROOT_LEVEL) {
        return LOS_OK;
    }

    LosProcessCB *run = OsCurrProcessGet();
    if (processCB->vProcessID.numbers[level].ownerContainer != run->containerBundle->pidContainer) {
        return -LOS_NOK;
    }

    return LOS_OK;
}

INT32 GetCurrPidByGlobalPid(UINT32 globalPid)
{
    LosProcessCB *pcb = OS_PCB_FROM_PID(globalPid);
    UINT32 ret ;
    UINT32 level = GetCurrPidLevel();
    ret = IsInSamePidContainer(pcb);
    if (ret == -LOS_NOK) {
        return ret;
    }

    return pcb->vProcessID.numbers[level].number;
}

STATIC PidContainer *CreatePidContainer(VOID)
{
    PidContainer *pidContainer;
    UINT32 size = sizeof(PidContainer);
    pidContainer = (PidContainer *)LOS_MemAlloc(m_aucSysMem1, size);

    if (pidContainer == NULL) {
        PRINT_ERR("Failed to malloc memory\n");
        return NULL;
    }
    (VOID)memset_s(pidContainer, sizeof(PidContainer), 0, sizeof(PidContainer));

    UINT32 intSave;
    SCHEDULER_LOCK(intSave);
    if (g_currentPidContainerNum > g_containerConfig.MaxPidContainer) {
        PRINT_ERR("CreatePidContainer failed, reach to max container config.\n");
        LOS_MemFree(m_aucSysMem1, pidContainer);
        return NULL;
    }
    g_currentPidContainerNum += 1;
    SCHEDULER_UNLOCK(intSave);

    return pidContainer;
}

STATIC INT32 AllocVpid(PidContainer *pidContainer, UINT32 *vpidIndex)
{
    UINT32 index = 0;

    for (index = 0; index < LOSCFG_BASE_CORE_PROCESS_LIMIT; index++) {
        if (pidContainer->vpidArray[index].status != VPID_STATUS_UNUSED) {
            continue;
        }
        pidContainer->vpidArray[index].status = VPID_STATUS_USED;
        *vpidIndex = index;
        break;
    }
    if (index == LOSCFG_BASE_CORE_PROCESS_LIMIT) {
        return -LOS_NOK;
    }

    return pidContainer->vpidArray[index].vpid;
}

VOID ExitPidContainer(LosProcessCB *processCB)
{
    if (processCB->containerBundle == NULL) {
        return;
    }
    if (processCB->containerBundle->pidContainer == NULL) {
        return;
    }
    UINT32 intSave = 0;
    SCHEDULER_LOCK(intSave);
    PidContainer *pidContainer = NULL;
    int level = processCB->containerBundle->pidContainer->level;
    int vpidIndex;
    pidContainer = processCB->containerBundle->pidContainer;
    while (level > PID_CONTAINER_ROOT_LEVEL) {
        vpidIndex = processCB->vProcessID.numbers[level].index;
        pidContainer->vpidArray[vpidIndex].status = VPID_STATUS_UNUSED;
        pidContainer = pidContainer->parent;
        level = level - 1;
    }
    SCHEDULER_UNLOCK(intSave);
}

INT32 LoopAllocVpid(LosProcessCB *processCB)
{
    PidContainer *pidContainer = processCB->containerBundle->pidContainer;
    UINT32 level = processCB->containerBundle->pidContainer->level;

    if (pidContainer == NULL) {
        return -LOS_NOK;
    }

    UINT32 vpidIndex = 0;
    UINT32 intSave = 0;
    SCHEDULER_LOCK(intSave);
    while (level > PID_CONTAINER_ROOT_LEVEL) {
        UINT32 vpid = AllocVpid(pidContainer, &vpidIndex);
        if (vpid == -LOS_NOK) {
            SCHEDULER_UNLOCK(intSave);
            return -LOS_NOK;
        }
        processCB->vProcessID.numbers[level].number = vpid;
        processCB->vProcessID.numbers[level].index = vpidIndex;
        processCB->vProcessID.numbers[level].ownerContainer = pidContainer;
        pidContainer->vpidArray[vpidIndex].processCB = processCB;
        pidContainer = pidContainer->parent;
        level = level - 1;
    }
    SCHEDULER_UNLOCK(intSave);
    return LOS_OK;
}

STATIC PidContainer *CreateNewPidContainer(PidContainer *pidContainer)
{
    PidContainer *newPidContainer = NULL;
    UINT32 index;
    UINT32 level = pidContainer->level + 1;

    if (level >= PID_CONTAINER_LEVEL_LIMIT) {
        PRINT_ERR("CLONE_NEWPID jsut Supports 3 layers \n");
	    return NULL;
    }

    newPidContainer = CreatePidContainer();
    if (newPidContainer == NULL) {
        return NULL;
    }

    for (index = 0; index < LOSCFG_BASE_CORE_PROCESS_LIMIT; index++) {
       newPidContainer->vpidArray[index].vpid = index + 1;
       newPidContainer->vpidArray[index].status = VPID_STATUS_UNUSED;
       newPidContainer->vpidArray[index].processCB = NULL;
    }

    newPidContainer->level = level;
    newPidContainer->parent = pidContainer;
    atomic_set(&newPidContainer->refCount, 1);
    ContainerAllocVnum(&(newPidContainer->containerBase.vnum));

    return newPidContainer;
}

PidContainer *HandlePidContainer(unsigned long flags, PidContainer *pidContainer)
{

    if (!(flags & CLONE_NEWPID)) {
        GetPidContainer(pidContainer);
        return pidContainer;
    }

    return CreateNewPidContainer(pidContainer);
}

INT32 PlaceProcessIntoPidContainer(LosProcessCB *childProcessCB) {
    int ret;
    ret = LoopAllocVpid(childProcessCB);
    if (ret != LOS_OK) {
       PRINT_ERR("Alloc vpid err.\n");
       return -LOS_NOK;
    }
    return LOS_OK;
}

INT32 ReplacePidContainerInBundle(ContainerBundle* bundle, struct PidContainer *targetPidContainer)
{
    DerefPidContainer(bundle->pidContainerForChildren);
    bundle->pidContainerForChildren = targetPidContainer;
    GetPidContainer(bundle->pidContainerForChildren);

    return LOS_OK;
}

VOID FreePidContainer(PidContainer *pidContainer)
{
    LOS_MemFree(m_aucSysMem1, pidContainer);
    pidContainer = NULL;

    UINT32 intSave;
    SCHEDULER_LOCK(intSave);
    g_currentPidContainerNum -= 1;
    SCHEDULER_UNLOCK(intSave);
}

VOID InitPidContainer(PidContainer *pidContainer)
{
    pidContainer->level = 0;
    pidContainer->parent = NULL;
    atomic_set(&pidContainer->refCount, 2);
    ContainerAllocVnum(&(pidContainer->containerBase.vnum));
}
#endif

